package com.ran.java_gobang.game;

import org.springframework.stereotype.Component;

import java.util.concurrent.ConcurrentHashMap;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: ran
 * Date: 2025-08-28
 * Time: 23:40
 */

// 房间管理器, 有唯一实例
@Component
public class RoomManager {
    // 房间id与房间
    private ConcurrentHashMap<String,Room> rooms = new ConcurrentHashMap<>();
    // 把玩家id与房间id关联起来
    private ConcurrentHashMap<Integer,String> userIdToRoomId = new ConcurrentHashMap<>();

    public void add(Room room, int userId1, int userId2) {
        rooms.put(room.getRoomId(),room);
        userIdToRoomId.put(userId1,room.getRoomId());
        userIdToRoomId.put(userId2,room.getRoomId());
    }

    public void remove(String roomId, int userId1, int userId2) {
        rooms.remove(roomId);
        userIdToRoomId.remove(userId1);
        userIdToRoomId.remove(userId2);
    }

    public Room getRoomByRoomId(String roomId) {
        return rooms.get(roomId);
    }

    public Room getRoomByUserId(int userId) {
        String roomId = userIdToRoomId.get(userId);
        if (roomId == null) {
            // 玩家没加入房间
            return null;
        }
        return rooms.get(roomId);
    }
}
